<?php

/**
 * 网址生成类
 */
class Url {

    private $mongodb = null;

    private $tableKey = array(0 => 'Y', 1 => 'W', 2 => 'L', 3 => 'U', 4 => 'f', 5 => 'y', 6 => 'H', 7 => 'Z', 8 => 'w', 9 => '7', 10 => '5', 11 => 'd', 12 => 'R', 13 => '4', 14 => 'F', 15 => 't', 16 => '0', 17 => 'S', 18 => 'P', 19 => '9', 20 => 'C', 21 => 'K', 22 => 'c', 23 => 's', 24 => 'Q', 25 => '1', 26 => 'G', 27 => 'i', 28 => 'o', 29 => 'b', 30 => 'j', 31 => 'r', 32 => 'v', 33 => 'm', 34 => '3', 35 => 'D', 36 => '6', 37 => 'X', 38 => '2', 39 => 'J', 40 => 'u', 41 => 'N', 42 => 'O', 43 => 'V', 44 => 'x', 45 => 'I', 46 => 'q', 47 => 'a', 48 => 'E', 49 => 'g', 50 => 'T', 51 => '8', 52 => 'n', 53 => 'e', 54 => 'M', 55 => 'l', 56 => 'p', 57 => 'k', 58 => 'z', 59 => 'B', 60 => 'h', 61 => 'A');

    public function __construct() {
        $mongoClient = new MongoClient('mongodb://127.0.0.1:27017');
        $this->mongodb = $mongoClient->test;
    }

    /**
     * 给定一个数字,转成自定义进制数据
     * @param $num int
     */
    public function trans($num) {
        $result = '';
        while ($num > 62) {
            $result = $this->tableKey[$num % 62] . $result;
            $num = floor($num / 62);
        }
        if ($num > 0) $result = $this->tableKey[$num] . $result;

        return $result;
    }

    // 得到自增的ID值
    public function getSn() {
        $mongoColl = $this->mongodb->selectCollection('cnt');
        $query = array('_id' => 1);
        $update = array('$inc' => array('sn' => 1));
        $tmp = $mongoColl->findAndModify($query, $update);
        return (int)$tmp['sn'];
    }

    // 查询生成的ID
    public function getId($oriurl) {
        $urlObj = $this->mongodb->selectCollection('url');
        $fields = array('_id' => 1);
        $condition = array('url' => $oriurl);
        $row = $urlObj->findOne($condition, $fields);
        if (!empty($row)) {
            return $row['_id'];
        }
        return false;
    }

    // 查询原网址
    public function getUrl($id) {
        $urlObj = $this->mongodb->selectCollection('url');
        $fields = array('url' => 1);
        $condition = array('_id' => $id);
        $row = $urlObj->findOne($condition, $fields);
        if (!empty($row)) {
            return $row['url'];
        }
        return false;
    }

    // 给定网址,生成短网址
    public function addUrl($oriurl) {

        // 判断URL是否已经存在
        $row = $this->getId($oriurl);
        if ($row) {
            return $row;
        }

        $sn = $this->getSn();
        $sns = $this->trans($sn);
        $row = array(
            '_id' => $sns,
            'url' => $oriurl,
            'hits' => 0
        );
        $urlObj = $this->mongodb->selectCollection('url');
        $urlObj->insert($row);
        return $sns;
    }

    // 访问加一
    public function incHits($id) {
        $urlObj = $this->mongodb->selectCollection('url');
        $where = array('_id' => $id);
        $data = array('$inc' => array('hits' => 1));
        $urlObj->update($where,$data);
    }


}